<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,
        body,
        #container {
          width: 100%;
          height: 100%;
        }
    </style>
</head>
<body>
<div id="container"></div>
<script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: "51f6623971cf8da6e494a34b5b950758",
    };
</script>
<script src="https://webapi.amap.com/loader.js"></script>
<script type="text/javascript">
    var map
    var AMapObj
    AMapLoader.load({
      key: "5b131ecf85d77d41cdba47a989b8bb76", //申请好的Web端开发者 Key，调用 load 时必填
      version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
    })
      .then((AMap) => {
        AMapObj = AMap
         map = new AMap.Map("container");
      })
      .catch((e) => {
        console.error(e); //加载错误提示
      });
</script>
<script>
    var port
    window.addEventListener("message", (event) => {
       if(event.data === "trans_port") {
         port = event.ports[0] // 拿到0端口
         //发送定位
        //  onNativeMessage()
         sendMessage({ type: 'alert', value: '端口拿到了' })
       }
       //接消息
        onNativeMessage()

    })
    // 发送消息给鸿蒙
    function sendMessage (obj) {
        if(port) {
            if(typeof obj !== "string") {
                port.postMessage(JSON.stringify(obj))
            }else {
                port.postMessage(obj)
            }

        }
    }

    function onNativeMessage () {
        if(port) {
            port.onmessage = (event) => {
               let res = event.data
               if(typeof res === 'string') {
                 res = JSON.parse(res)
               }
               map.setCenter([res.longitude, res.latitude])
               map.setZoom(15)

              let marker = new AMapObj.Marker({
                 icon: "http://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
                 position: [res.longitude, res.latitude],
                 offset: new AMapObj.Pixel(-13, -30)
               });
               marker.setMap(map);
            }
        }

    }

</script>
</body>
</html>